package com.hex.ds.hdrs.watch.service;

import com.hex.bigdata.hbda.utils.DateUtil;
import com.hex.bigdata.hbda.utils.StringUtils;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.utils.BaseUtil;
import com.hex.ds.hdrs.log.po.MailSendLog;
import com.hex.ds.hdrs.log.po.RunningStateLog;
import com.hex.ds.hdrs.log.service.MailSendLogService;
import com.hex.ds.hdrs.log.service.RunningStateLogService;
import com.hex.ds.hdrs.log.service.SmsSendLogService;
import com.hex.ds.hdrs.warn.dto.WarnSendMethodDto;
import com.hex.ds.hdrs.warn.po.WarnSendLog;
import com.hex.ds.hdrs.warn.po.WarnSendMethod;
import com.hex.ds.hdrs.warn.service.WarnSendLogService;
import com.hex.ds.hdrs.warn.service.WarnSendMethodService;
import com.hex.ds.hdrs.watch.vo.ImageResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.naming.Context;
import java.util.*;

/**
 * @author lwz
 * @date 2021-02-23
 * @des
 */
@Slf4j
// @Service  邮件发生不需要
public class WatchSendService {

    @Autowired
    private RunningStateLogService runningStateLogService;

    @Autowired
    private MailSendLogService mailSendLogService;

    @Autowired
    private SmsSendLogService smsSendLogService;

    @Autowired
    private MailService mailService;

    @Autowired
    private WarnSendMethodService warnSendMethodService;

    @Autowired
    private WarnSendLogService warnSendLogService;

    /**
     * 将RunningStateLog 中需要发送邮件和短信的预警转存到发送记录表中
     */
    public void noticLogToSendLog() {
        log.info("运行日志转换邮件、短信发送记录【WatchSendService.noticLogToSendLog-开始】");
        try {
            List<RunningStateLog> runningStateLogList = this.runningStateLogService.findNeedSendStateLog();
            for (RunningStateLog stateLog : runningStateLogList) {
                try {
                    String subject = stateLog.getRemindTitle();
                    StringBuffer sb=new StringBuffer();
                    sb.append("尊敬的管理员，您好！"+"\r\n").append(stateLog.getRemindContent());
                    String content = String.valueOf(sb);
                    String mailAddress = stateLog.getMailAddress();
                    String phone = stateLog.getPhones();
                    if (Const.MAIL_NOTICE_OPEN.equals(stateLog.getIsMailNotic()) && StringUtils.isNotBlank(mailAddress)) {
                        this.mailSendLogService.add(mailAddress, subject, content, false);
                    }
                    if (Const.SMS_NOTICE_OPEN.equals(stateLog.getIsSmsNotic()) && StringUtils.isNotBlank(phone)) {
                        String[] phones = phone.split(",");
                        for (String ph : phones){
                            this.smsSendLogService.add(ph, content);
                        }
                    }
                    this.runningStateLogService.update(Const.WARN_HAS_SEND, DateUtil.getCurrentTime(), stateLog.getPkId());
                }catch (Exception e){

                    log.error("运行日志pkId = {} 转换失败：{}" , stateLog.getPkId(), e.getMessage(),e);
                }
            }
        }catch (Exception e){

            log.error("运行日志转换邮件、短信发送记录异常：{}" , e.getMessage(),e);
        }
        log.info("运行日志转换邮件、短信发送记录【WatchSendService.noticLogToSendLog-结束】");
    }

    public void mailSend(){
        log.info("邮件发送【WatchSendService.mailSend-开始】");
        try {
            //List<MailSendLog> mailSendLogList = this.mailSendLogService.qryNotSendLog();
            Map<String,String> map = new HashMap<>();
            map.put("sendStatus",Const.WARN_SEND_STATUS_NO);
            List<WarnSendMethodDto> list = this.warnSendMethodService.selectWarnList(map);
            if (!CollectionUtils.isEmpty(list)){
                for (WarnSendMethodDto dto : list){
                    if (Const.MAIL_IS_TXT.equals(dto.getIsHtml())){
                        this.sendTextMail(dto);
                    }
//                if (Const.MAIL_IS_HTML.equals(mailSendLog.getIsHtml())){
//                    this.sendHtmlMail(mailSendLog);
//                }
                }
            }
        }catch (Exception e){

            log.error("邮件发送异常：{}" , e.getMessage(),e);
        }
        log.info("邮件发送【WatchSendService.mailSend-结束】");
    }

    public void sendTextMail(WarnSendMethodDto dto){
        String sendStatus = Const.MAIL_SEND_SUCCESS;
        try {
            String subject = dto.getSubject();
            String content = dto.getContent();
            String[] toWho = StringUtils.split(dto.getToAddr(),",");
            String[] ccPeoples = StringUtils.split(dto.getCcAddr(),",");
            String[] bccPeoples = StringUtils.split(dto.getBccAddr(),",");
            String[] attachments = StringUtils.split(dto.getAttachmentPath(),",");
            //this.mailService.sendSimpleTextMailActual(subject, content, toWho, ccPeoples, bccPeoples, attachments);
            //添加日志
            this.saveWarnSendLog(dto,Const.WARN_SEND_STATUS_SUCCESS);
        }catch (Exception e){
            this.saveWarnSendLog(dto,Const.WARN_SEND_STATUS_ERROR);
            sendStatus = Const.MAIL_SEND_FAIL;
            log.error("邮件发送记录 pkId = {} 发送失败：{}",dto.getPkId(),e.getMessage(),e);
        }finally {
            this.mailSendLogService.updateSendStatus(dto.getPkId(), sendStatus, DateUtil.getCurrentTime());
        }
    }

    public void sendHtmlMail(MailSendLog mailSendLog){
        String sendStatus = Const.MAIL_SEND_SUCCESS;
        try {
            String subject = mailSendLog.getSubject();
            String content = mailSendLog.getContent();
            String[] toWho = StringUtils.split(mailSendLog.getToAddr(),",");
            String[] ccPeoples = StringUtils.split(mailSendLog.getCcAddr(),",");
            String[] bccPeoples = StringUtils.split(mailSendLog.getBccAddr(),",");
            String[] attachments = StringUtils.split(mailSendLog.getAttachmentPath(),",");

            String templateName = null;
            Context context = null;
            Set<ImageResource> imageResourceSet = new HashSet<>();
            //this.mailService.sendHtmlTemplateMailActual(subject, toWho, ccPeoples, bccPeoples, attachments, templateName, context, imageResourceSet);
        }catch (Exception e){

            sendStatus = Const.MAIL_SEND_FAIL;
            log.error("邮件发送记录 pkId = {} 发送失败：{}", mailSendLog.getPkId(),e.getMessage(),e);
        }finally {
            this.mailSendLogService.updateSendStatus(mailSendLog.getPkId(), sendStatus, DateUtil.getCurrentTime());
        }
    }

    public void smsSend(){
        log.info("短信发送【WatchSendService.smsSend-开始】");
        try {

        }catch (Exception e){

            log.error("短信发送异常：{}" , e.getMessage());
        }
        log.info("短信发送【WatchSendService.smsSend-结束】");
    }

    /**
     * @Method: saveWarnSendLog
     * @Param: [dto, status]
     * @Return: void
     * @Description: 发送日志
     * @Author: ji.tang
     * @Date: 2022/4/29 18:06
     * @Version: V1.0
     */
    public void saveWarnSendLog(WarnSendMethodDto dto,String status){
        WarnSendLog warnSendLog = new WarnSendLog();
        warnSendLog.setPkId(BaseUtil.getPkId());
        warnSendLog.setSendTime(DateUtil.getCurrentTime());
        warnSendLog.setSendStatus(status);
        warnSendLog.setWarnId(dto.getPkId());
        warnSendLog.setCrtTs(BaseUtil.getUserId());
        warnSendLog.setUpUser(BaseUtil.getUserId());
        warnSendLog.setCrtTs(DateUtil.getCurrentTime());
        warnSendLog.setUpTs(DateUtil.getCurrentTime());
        //1.新增日志
        this.warnSendLogService.insert(warnSendLog);
        //2.修改告警发送方式
        this.updateSendMethod(dto,status);
    }

    /**
     * @Method: updateSendMethod
     * @Param: [dto, status]
     * @Return: void
     * @Description:  修改告警发送方式
     * @Author: ji.tang
     * @Date: 2022/5/20 17:24
     * @Version: V1.0
     */
    private void updateSendMethod(WarnSendMethodDto dto, String status) {
        WarnSendMethod method = new WarnSendMethod(dto.getPkId(),DateUtil.getCurrentTime(),status,BaseUtil.getUserId(),DateUtil.getCurrentTime());
        this.warnSendMethodService.edit(method);
    }
}
